import React        from 'react';

import Nav          from '../../config/Navigator';
import Base         from '../../components/BaseComponent';
import Cart         from '../icon/Cart';
import {Token}      from "../../utils/Storage";
import './cartCount.scss';

export default class extends Base {

    state = {count: this.props.value || 0};

    add(){
        var {count} = this.state;
        _.invoke(this.props, 'beforeAdd', ++count).then(r => {
            if(r === true){
                this.setState({count});
            }
        });
    }

    minus(){
        var {count} = this.state;
        _.invoke(this.props, 'beforeMinus', --count).then(r => {
            if(r === true){
                this.setState({count});
            }
        });
    }

    animate(){
        if(!Token.isActive()){
            return confirm('请先激活会员!') ? this.router.push(Nav.active()) : '';
        }
        var target = _.invoke(this.props, 'target');
        if(target){
            var _target = target.cloneNode(true), cart = document.getElementById('badge').parentNode;
            var targetRect = target.getBoundingClientRect();
            target.parentNode.parentNode.parentNode.parentNode.appendChild(_target);
            _target.style.top = `calc(${targetRect.bottom}px - 1.9rem)`;
            _target.classList.add('move');
            setTimeout(() => {
                _target.classList.add('moving');
                _target.style.top =  `calc(${cart.getBoundingClientRect().top}px - .7rem)`;
                setTimeout(() => {
                    _target.remove();
                }, 1050);
            });
            this.add();
        }
    }

    render(){
        var {count} = this.state;
        return (
            <div className="cart-count flex-avg">
                {count === 0 ?
                    <div className="cc-icon flex-avg" onClick={() => this.animate()}>
                        <Cart size=".3rem"/>
                    </div> :
                    <div className="cc-btn flex-avg">
                        <div className="ccb flex-avg" onClick={() => this.minus()}>-</div>
                        <div className="cct">{count}</div>
                        <div className="ccb flex-avg" onClick={() => this.add()}>+</div>
                    </div>
                }
            </div>
        );
    }

}
